I'm just trying to upsert a key value pair i.e. {mark : done} to my Mongo database using id that I have stored in an array.
But for the life of me I can't figure out why if I use a for loop it works fine. But if I use a forEach loop, it gives me a "Cannot use a session that has ended" Error.
I'm hoping someone SO assist in explaining why this happens
import { MongoClient } from "mongodb";
const uri = "mongodb://localhost:27018/";
const client = new MongoClient(uri);
async function updateMongo1() {
const db = client.db("testDB");
const coll = db.collection("testCollection");
await client.connect();
try {
let array = [
"2021-10-18",
"2021-10-17",
"2021-10-16",
"2021-10-15",
"2021-10-14",
];
for (let i = 0; i < array.length; i++) {
await coll.updateOne(
{ _id: array[i] },
{ $set: { mark: "done" } },
{ upsert: true }
);
}
} catch (e) {
console.error(e.message);
} finally {
await client.close();
}
}
async function updateMongo2() {
const db = client.db("testDB");
const coll = db.collection("testCollection");
await client.connect();
try {
let array = [
"2021-10-18",
"2021-10-17",
"2021-10-16",
"2021-10-15",
"2021-10-14",
];
array.forEach(async (element) => {
await coll.updateOne(
{ _id: element },
{ $set: { mark: "done" } },
{ upsert: true }
);
});
} catch (e) {
console.error(e.message);
} finally {
await client.close();
}
}
(async () => {
//await updateMongo1(); //-> this works
await updateMongo2(); //-> this gives "MongoExpiredSessionError: Cannot use a session that has ended" what gives??
})();
Please let me know why this happens?
The element variable is an array e.g. ["2021-10-18"]. In the second implementation, you were meant to access element[0] but forgot to so you put an array into the _id field.
I don't know if that's what's specifically causing your error but it is an error in the implementation.